use base::client::Client;
use file::{do_upload, get_dir};
use lazy_static::lazy_static;
use tracing::{instrument, warn};
use tracing_subscriber::prelude::*;
use warp::multipart::FormData;
use warp::Filter;

#[instrument(skip_all, name = "main")]
#[tokio::main]
async fn main() {
    base::trace_warn!();

    lazy_static! {
        static ref CLIENT: Client = Client::new();
    }

    let get = warp::path("file")
        .and(warp::path::peek())
        .map(|peek| warn!("{:?}", peek))
        .untuple_one()
        .and(warp::fs::dir(get_dir()))
        .with(base::cors!());

    let upload = warp::path("file")
        .and(warp::path::param())
        .and(warp::post())
        .and(warp::multipart::form().max_length(None))
        .and_then(move |cmd: String, form: FormData| async { do_upload(cmd, form, &CLIENT).await });

    let post = upload.with(base::cors!());
    let opt = base::opt!();

    let route = get.or(opt).or(post);

    warn!("listening on 127.0.0.1:9982");

    warp::serve(route).run(([0, 0, 0, 0], 9982)).await;
}
